package com.abe.mvp.view.activity;

import java.util.List;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.abe.config.Constants;
import com.abe.config.ExerciseSTReportUtil;
import com.abe.config.SettingParam;
import com.abe.mvp.contact.WebServerContact;
import com.abe.mvp.model.bean.MenuBean;
import com.abe.mvp.model.bean.SettingBean;
import com.abe.mvp.model.bean.http.ScanBean;
import com.abe.mvp.model.bean.http.UserBean;
import com.abe.mvp.presenter.HttpQRCodePresenterImp;
import com.abe.mvp.presenter.HttpScanLoginPresenter;
import com.abe.mvp.view.activity.base.BaseActivity;
import com.abe.mvp.view.adapter.SettingMenuAdapter;
import com.abe.strengthtrainer.R;
import com.abe.utils.JsonHelper;
import com.abe.utils.SPUtils;
import com.abe.utils.ThreadPoolUtils;
import com.squareup.picasso.Picasso;

/**
 * @author yaopeng
 * @see 登录页
 * @see 登录方式:刷卡登录、微信扫码登录
 * */
@ContentView(R.layout.activity_tm_login)
public class LoginActivity extends BaseActivity implements
		WebServerContact.QRCodeView, WebServerContact.ScanLoginView,
		OnItemClickListener {

	private WebServerContact.QRCodePresenter qrCodePresenter;
	private WebServerContact.ScanLoginPresenter scanLoginPresenter;

	private SettingBean settingBean;

	@ViewInject(R.id.show_exercise_button_back)
	private LinearLayout show_exercise_button_back;
	@ViewInject(R.id.show_exercise_logo)
	private ImageView show_exercise_logo;

	@ViewInject(R.id.tabmenu_layout)
	private ImageView tabmenu_layout;

	@ViewInject(R.id.login_grid_menu)
	private GridView login_grid_menu;
	private List<MenuBean> loginMenuBeans;
	private SettingMenuAdapter adapter;

	@ViewInject(R.id.login_layout_qr_code)
	private LinearLayout login_layout_qr_code;
	@ViewInject(R.id.login_layout_cardreader)
	private LinearLayout login_layout_cardreader;
	@ViewInject(R.id.login_image_qr_code)
	private ImageView login_image_qr_code;
	@ViewInject(R.id.login_image_cardreader)
	private ImageView login_image_cardreader;

	private String current_login_name;
	/** 轮询线程运行 */
	private boolean qr_code_run;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initBackground();
	}

	@Override
	protected void onResume() {
		super.onResume();
		/** 初始化APP当前用户 */
		current_login_name = "";
		qr_code_run = false;
		/** 默认游客 */
		String tourist_json = JsonHelper.toJson(SettingParam.getTouristUser());
		SPUtils.put(getApplicationContext(), SettingParam.SP_CurrentUser,
				tourist_json);
		settingBean = SettingParam.getSettingBean();
		/** 是否支持二维码扫描登录 */
		if (settingBean.getLoginType() == SettingParam.loginType_scan
				|| settingBean.getLoginType() == SettingParam.loginType_all) {
			qrCodePresenter = new HttpQRCodePresenterImp(this);
			scanLoginPresenter = new HttpScanLoginPresenter(this);
			/** 请求二维码图片 */
			qrCodePresenter.getQRCode();
		}
		initView();
	}

	private void initView() {
		login_grid_menu.setVisibility(View.VISIBLE);
		show_exercise_button_back.setVisibility(View.INVISIBLE);
		show_exercise_logo.setVisibility(View.VISIBLE);
		login_layout_qr_code.setVisibility(View.GONE);
		login_layout_cardreader.setVisibility(View.GONE);
		
		loginMenuBeans = SettingParam.getLoginMenuBeans();
		adapter = new SettingMenuAdapter(this, loginMenuBeans, scale);
		login_grid_menu.setNumColumns(loginMenuBeans.size());
		LayoutParams params = login_grid_menu.getLayoutParams();
		params.width = (int) (scale * 320 * loginMenuBeans.size());
		login_grid_menu.setLayoutParams(params);
		login_grid_menu.setAdapter(adapter);
		login_grid_menu.setOnItemClickListener(this);
	}

	private void initBackground() {
		/** 菜单页背景 */
		Picasso.with(this).load(R.drawable.run_image_bg_05).centerCrop()
				.placeholder(R.drawable.app_theme_bg).resize(1152, 720)
				.into(tabmenu_layout);
	}

	/** 隐藏二维码 */
	@Event(value = R.id.login_layout_qr_code, type = View.OnClickListener.class)
	private void hideQrCode(View view) {
		login_grid_menu.setVisibility(View.VISIBLE);
		login_layout_qr_code.setVisibility(View.GONE);
	}

	/** 隐藏等待刷卡 */
	@Event(value = R.id.login_layout_cardreader, type = View.OnClickListener.class)
	private void hideCardReader(View view) {
		login_grid_menu.setVisibility(View.VISIBLE);
		login_layout_cardreader.setVisibility(View.GONE);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
		SettingBean bean = SettingParam.getSettingBean();
		switch (pos) {
		case 0:
			/** 设置 */
			gotoActivityForResult(SettingActivity.class, 1);
			break;
		case 1:
			switch (bean.getLoginType()) {
			case SettingParam.loginType_no:
				/** 体验 */
				/** 游客信息 */
				current_user = SettingParam.getTouristUser();
				gotoExerciseMenu();
				break;
			case SettingParam.loginType_scan:
				login_grid_menu.setVisibility(View.GONE);
				/** 显示二维码 */
				login_layout_qr_code.setVisibility(View.VISIBLE);
				/** 开启轮询登录信息 */
				scanLoginPresenter.getScanLogin("");
				break;
			case SettingParam.loginType_swingcard:
				login_grid_menu.setVisibility(View.GONE);
				/** 显示刷卡图片 */
				login_layout_cardreader.setVisibility(View.VISIBLE);
				break;
			case SettingParam.loginType_all:
				login_grid_menu.setVisibility(View.GONE);
				/** 显示二维码 */
				login_layout_qr_code.setVisibility(View.VISIBLE);
				/** 开启轮询登录信息 */
				scanLoginPresenter.getScanLogin("");
				break;
			}

			break;
		case 2:
			switch (bean.getLoginType()) {
			case SettingParam.loginType_scan:
				/** 体验 */
				/** 游客信息 */
				current_user = SettingParam.getTouristUser();
				gotoExerciseMenu();
				break;
			case SettingParam.loginType_swingcard:
				login_grid_menu.setVisibility(View.GONE);
				/** 显示刷卡图片 */
				login_layout_cardreader.setVisibility(View.VISIBLE);
				break;
			case SettingParam.loginType_all:
				login_grid_menu.setVisibility(View.GONE);
				/** 显示刷卡图片 */
				login_layout_cardreader.setVisibility(View.VISIBLE);
				break;
			}
			break;
		case 3:
			/** 体验 */
			/** 游客信息 */
			current_user = SettingParam.getTouristUser();
			gotoExerciseMenu();
			break;
		}
	}

	@Override
	public void onScanLoginSuccess(UserBean bean) {
		if (bean != null) {
			current_login_name = bean.getUserName();
			if (!current_login_name.equals("")) {
				current_user.setFlag(SettingParam.flag_user_scanlogin);
				current_user.setUser(bean);
				gotoExerciseMenu();
			} else {
				ThreadPoolUtils.execute(new CheckUserThread());
			}
		} else {
			ThreadPoolUtils.execute(new CheckUserThread());
		}
	}

	@Override
	public void onGetQRCodeSuccess(ScanBean bean) {
		/** 二维码图片 */
		Picasso.with(this).load(bean.getImagePath()).into(login_image_qr_code);
	}

	@Override
	public void onRequestFail(String errorMsg) {
		showToast(errorMsg);
	}

	@Override
	public void onFinish(int type) {

	}

	class WaitUserThread implements Runnable {
		@Override
		public void run() {
			qr_code_run = true;
			/** 根据登录名来发起查询 */
			while (qr_code_run && current_login_name.equals("")) {
				try {
					/** 每隔1000ms查询一次 */
					Thread.sleep(1000);
					scanLoginPresenter.getScanLogin("");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	class CheckUserThread implements Runnable {
		@Override
		public void run() {
			try {
				/** 每隔1000ms查询一次 */
				Thread.sleep(500);
				scanLoginPresenter.getScanLogin("");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/** 读卡等待线程 */
	class ReadCardThread implements Runnable {
		private boolean cardFlg;
		private String cardNo;

		public ReadCardThread() {
			cardNo = "";
		}

		@Override
		public void run() {
			/** 当卡号为空且为读卡状态 */
			while (cardNo.equals("") && cardFlg) {
				/** 此处读卡号 */
				if (!"".equals(cardNo)) {
					/** 对卡号进行验证 */

				}
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}
	}

	private void gotoExerciseMenu() {
		if (current_user != null) {
			/** 缓存 */
			SPUtils.put(getApplicationContext(), SettingParam.SP_CurrentUser,
					JsonHelper.toJson(current_user));
		} else {
			System.out.println("current_user==null");
		}
		SPUtils.put(getApplicationContext(), SettingParam.SP_LANGUAGE_KEY,
				SettingParam.getSettingBean().getLanguage());
		ExerciseSTReportUtil.clearExercise();
		/** 设置 */
		gotoActivityForResult(ExerciseLanguageActivity.class, 1);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null) {
			int extra = data.getIntExtra("extra", Constants.ExitApp);
			Intent intent = new Intent();
			if (extra == Constants.SettingLanguage) {
				intent.putExtra("extra", extra);
			} else {
				intent.putExtra("extra", Constants.ExitApp);
			}
			setResult(RESULT_OK, intent);
			back();
		}
	}

}
